package com.byit.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.plugins.Page;
import com.byit.builder.MapBuilder;
import com.byit.constant.DefaultValue;
import com.byit.domain.AppComplaint;
import com.byit.enums.PromptInfo;
import com.byit.log.ChannelType;
import com.byit.log.Log;
import com.byit.log.OperatorType;
import com.byit.msg.MessageResult;
import com.byit.service.IAppComplaintService;
import com.byit.shrio.session.SessionHelper;
import com.byit.utils.MinioUtil;
import com.byit.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName AppComplaintController
 * @Description 投诉建议
 * @Author lxp
 * @Date 2019-01-03 17:53
 **/
@RestController
@RequestMapping("/api/sys/appComplaint")
public class AppComplaintController {


    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IAppComplaintService appComplaintService;

    @Autowired
    private MinioUtil minioUtil;


    /**
     * 新增或修改投诉建议信息
     *
     * @param session
     * @param appComplaint
     * @return
     */
    @PostMapping("/add")
    @Log(title = "投诉建议", operate = OperatorType.DATA_INSERT, channel = ChannelType.WEB_INTER)
    public Object insertAppComplaint(HttpSession session, AppComplaint appComplaint) {


        Long userId = SessionHelper.getUserId(session);
        try {
            if (null == appComplaint) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }

            appComplaint.setCreateTime(new Date());
            appComplaint.setUpdateTime(new Date());
            //// 加密用户密码

            appComplaintService.insertOrUpdate(appComplaint);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 新增或修改投诉建议信息
     *
     * @param session
     * @param appComplaint
     * @return
     */
    @PostMapping("/edit")
    @Log(title = "投诉建议", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
    public Object edit(HttpSession session, AppComplaint appComplaint) {


        Long userId = SessionHelper.getUserId(session);
        //// 加密用户密码
        appComplaint.setOperationId(userId);
        try {
            if (null == appComplaint) {
                return MessageResult.warpper(PromptInfo.ERROR_PARAM_NOT_NULL);
            }
            if (appComplaint.getId() != 0 && appComplaint.getId() != null) {
                appComplaint.setUpdateTime(new Date());
            }
            //// 加密用户密码

            appComplaintService.insertOrUpdate(appComplaint);
            return MessageResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return MessageResult.error(e);
        }
    }

    /**
     * 通过Id查询投诉建议
     *
     * @param id
     * @return
     */
    @GetMapping("/details")
    @Log(title = "投诉建议", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object selectAppComplaintById(@RequestParam("id") Integer id) {
        AppComplaint appComplaint = appComplaintService.selectById(id);
        return MessageResult.success(appComplaint);
    }

    /**
     * 按照条件查询投诉建议
     *
     * @param session
     * @param title
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    @Log(title = "投诉建议", operate = OperatorType.DATA_SELECT, channel = ChannelType.WEB_INTER)
    public Object selectAppComplaintAll(HttpSession session,
                                        @RequestParam(value = "title", defaultValue = "") String title,
                                        @RequestParam(value = "type", defaultValue = "") String type,
                                        @RequestParam(value = "searchContent", defaultValue = "") String searchContent,
                                        @RequestParam(value = "manageResult", defaultValue = "") String manageResult,
                                        @RequestParam(value = "page", defaultValue = DefaultValue.PAGE_FIRST) int page,
                                        @RequestParam(value = "limit", defaultValue = DefaultValue.PAGE_SIZE) int limit) {
        Page<AppComplaint> pageInfo = new Page<>(page, limit);
        Map<String, Object> params = MapBuilder.newMap(3)
                .setParam("type", type)
                .setParam("manageResult", manageResult)
                .setParam("title", title)
                .ok();
        if (null != title && !"".equals(title)) {
            params.put("title", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(title) + "%");
        }
        if (null != searchContent && !"".equals(searchContent)) {
            params.put("searchContent", "%" + StringUtil.decodeSpecialCharsWhenLikeUseBackslash(searchContent) + "%");
        }
        Page<JSONObject> result = appComplaintService.selectAppComplaintAll(pageInfo, params);

        return MessageResult.warpper(PromptInfo.SYS_SECCUSS, result);
    }

    /**
     * 逻辑删除投诉建议信息
     *
     * @param session
     * @param ids
     * @return
     */
    @PostMapping("/del")
    @Log(title = "投诉建议", operate = OperatorType.DATA_DELETE, channel = ChannelType.WEB_INTER)
    public Object delAppComplaintByIds(HttpSession session, @RequestParam("ids") String ids) {
        Long userId = SessionHelper.getUserId(session);
        List<Long> idList = StringUtil.splitLong(ids, ",");
        Map<String, Object> map = MapBuilder.newMap(3).setParam("updateTime", new Date()).setParam("operId", userId).ok();

        for (Long id : idList) {
            map.put("id", id);
            appComplaintService.delAppComplaintById(map);
        }
        return MessageResult.success();
    }

    /**
     * 上传图片
     */
    @PostMapping("/upload")
    @Log(title = "投诉建议", operate = OperatorType.IMG_UPLOAD, channel = ChannelType.WEB_INTER)
    public Object upload(@RequestParam("file") MultipartFile file) {
        try {
            if (null == file) {
                return MessageResult.error("文件不能为空");
            } else {
                JSONObject jsonObject = minioUtil.uploadFile(file.getInputStream(),
                        file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")), "AppComplaint/");
                if ("1".equals(jsonObject.getString("flag"))) {
                    return MessageResult.error("上传失败");
                } else {
                    jsonObject.getString("path");
                    return MessageResult.success();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            return MessageResult.error(e);
        }


    }


    /**
     * 审核投诉
     *
     * @param id
     * @return
     */
    @PostMapping("/deal")
    @Log(title = "投诉建议", operate = OperatorType.DATA_UPDATE, channel = ChannelType.WEB_INTER)
    public Object publishAppNews(@RequestParam("id") Long id,
                                 @RequestParam(value = "remark", defaultValue = "") String remark,
                                 @RequestParam("deal") Integer manage_result) {
        AppComplaint appComplaint = appComplaintService.selectById(id);
        appComplaint.setId(id);
        appComplaint.setRemark(remark);
        appComplaint.setManageResult(manage_result);
        try {

            appComplaintService.updateById(appComplaint);
        } catch (Exception e) {
            return MessageResult.error(e.getMessage());
        }
        return MessageResult.success();
    }

}
